package com.frxuexi.park2210.user

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.EncryptUtils
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.entity.UserBean
import com.frxuexi.lib_base.mvvm.BaseActivity
import com.frxuexi.lib_base.net.Const
import com.frxuexi.park2210.R
import com.frxuexi.park2210.databinding.ActivityLoginBinding
import com.google.gson.Gson
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.lang.StringBuilder

@Route(path = "/app/LoginActivity")
@AndroidEntryPoint
class LoginActivity : BaseActivity<ActivityLoginBinding,UserViewModel>() {

    override fun initData() {
        vm.loginSuc.observe(this){
            val userBean = Gson().fromJson(it, UserBean::class.java)
            SPUtils.getInstance().put(Const.TOKEN,userBean.token)
            SPUtils.getInstance().put(Const.UID,userBean.uId)
            SPUtils.getInstance().put(Const.UNAME,userBean.uName)
            Log.i("===",it)
//            if(userBean.uName.contains("admin")) {
                ARouter.getInstance().build("/app/MainActivity").navigation()
//            }else{
//                ARouter.getInstance().build("/shop/ShopActivity").navigation()
//            }

            finish()
        }
    }

    override fun initView() {

        if(!SPUtils.getInstance().getString(Const.TOKEN,"").isNullOrEmpty()){
            ARouter.getInstance().build("/app/MainActivity").navigation()
            finish()
            return
        }

        binding.btnLogin.setOnClickListener {
            val name = binding.etName.text.toString()
            val pass = binding.etPass.text.toString()
            if(name.isNullOrEmpty() || pass.isNullOrEmpty()){
                ToastUtils.showLong("输入内容不能为空")
                return@setOnClickListener
            }
            if(!name.matches(Regex("[A-z0-9]{2,9}"))){
                ToastUtils.showLong("不是合法用户名")
                return@setOnClickListener
            }

            val time = (System.currentTimeMillis() / 1000).toString()
            val map = mutableMapOf<String, String>()
            map["time"]=time
            map["uName"]=name
            map["uPwd"]=pass
            val sb = StringBuilder()
            sb.append(name).append(pass).append(time).append("tamboo")

            val sign = EncryptUtils.encryptMD5ToString(sb.toString()).toLowerCase()
            map["sign"]=sign
            vm.login(map)

        }
    }

}